<template>
	<van-dialog
		class="app-modal"
		:duration="duration"
		v-model:show="visible"
		:closeable="false"
		lazy-render
		close-on-popstate
		:close-on-click-overlay="false"
		:showConfirmButton="false"
	>
		<component
			:is="props.view.codeName"
			:context="props.context"
			:viewParams="props.viewParams"
			:name="props.view.codeName"
			openType="MODAL"
			@view-action="handleViewEvent"
			@view-init="handleViewInit"
			@view-destroy="handleViewDestroy"
		/>
	</van-dialog>
</template>
<script lang="ts" setup>
import { IContext, IOpenViewResult, IParam, IViewAbility } from '@/core';
import { IViewDetail, IEvent } from '@/core';

interface ModalProps {
	view: IViewDetail;
	context: IContext;
	viewParams: IParam;
}
const visible = ref<boolean>(false);
const duration: number = 0.3;
const props = withDefaults(defineProps<ModalProps>(), {});

onMounted(() => {
	// 显示模态组件打开动画效果
	setTimeout(() => {
		visible.value = true;
	}, 1);
});

const closeModal = () => {
	// 显示模态组件关闭动画效果
	visible.value = false;
	setTimeout(handleClose, duration * 1000);
};

const emit = defineEmits(['modal-action']);

let result: IOpenViewResult = { ok: true, data: [] };
const handleViewEvent = (
	name: string,
	action: IEvent<string>,
	data: IParam
) => {
	if (Object.is(action, 'viewDataChange')) {
		if (data && Array.isArray(data) && data.length > 0) {
			result = { ok: true, data: JSON.parse(JSON.stringify(data)) };
		}
	} else if (
		Object.is(action, 'viewDataActive') ||
		Object.is(action, 'viewClose')
	) {
		if (data && Array.isArray(data) && data.length > 0) {
			result = { ok: true, data: JSON.parse(JSON.stringify(data)) };
		}
		closeModal();
	}
};

const handleViewDestroy = (name: string, data: IParam) => {
	emit('modal-action', result);
};
const handleViewInit = (name: string, data: IViewAbility) => {};
const handleClose = () => {
	emit('modal-action', result);
};
</script>
